package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.constant.UserRegisterConstant;
import com.sky.constant.WeiXinUrlConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author moningxi
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private WeChatProperties weChatProperties;
    @Resource
    private UserMapper userMapper;

    /**
     * 微信登录或者注册
     */
    @Override
    public UserLoginVO loginOrRegister(UserLoginDTO dto) {
        String openid = getOpenId(dto.getCode());
        if (StringUtils.isBlank(openid)) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        // 查询用户是否注册
        User user = userMapper.getByOpenId(openid);
        if (user == null) {
            //注册用户
            user = new User();
            user.setOpenid(openid);
            user.setName(UserRegisterConstant.USER_NAME);
            user.setSex(UserRegisterConstant.USER_SEX);
            user.setAvatar(UserRegisterConstant.USER_AVATAR);
            user.setCreateTime(LocalDateTime.now());
            userMapper.save(user);
        }

        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setId(user.getId());
        userLoginVO.setOpenid(user.getOpenid());
        return userLoginVO;
    }

    /**
     * 调用微信登录接口获取openId
     */
    private String getOpenId(String code) {
        // 调用微信登录接口获取openId
        Map<String, String> params = new HashMap<>();
        params.put("appid", weChatProperties.getAppid());
        params.put("secret", weChatProperties.getSecret());
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");
        String response = HttpClientUtil.doGet(WeiXinUrlConstant.WEI_XIN_LOGIN, params);
        log.info("微信登录返回的数据：{}", response);
        JSONObject jsonObject = JSONObject.parseObject(response);
        return jsonObject.getString("openid");
    }
}
